﻿using System;
using System.Configuration;
using System.Net;
using System.Web.Script.Serialization;
using log4net;

namespace OpenWaves.EPiServer.BrightcoveVideoCloudProperty
{
    public class VideoCloudService
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof (VideoCloudService));
        private readonly Uri baseQueryUrl = new Uri("http://api.brightcove.com/services/library");

        public static VideoCloudPropertySettings Configuration
        {
            get
            {
                var settings = ConfigurationManager.GetSection("videoCloudConfig") as VideoCloudPropertySettings;
                if (settings == null)
                    throw new ConfigurationErrorsException("Video cloud property is not configured properly.");

                return settings;
            }
        }

        public object GetVideos(Query query)
        {
            return GetResult(query.ToRelativeUri());
        }

        private object GetResult(Uri query)
        {
            var webClient = new WebClient();

            var absoluteQuery = new Uri(baseQueryUrl, query);
            if (absoluteQuery.IsAbsoluteUri == false)
            {
                throw new InvalidOperationException(
                    string.Format("Couldn't query GSA. Please fix the GSA url in configuration file. Used url = {0}",
                                  absoluteQuery));
            }

            try
            {
                Log.InfoFormat("Querying GSA, url = {0}", absoluteQuery);
                string result = webClient.DownloadString(absoluteQuery);
                Log.InfoFormat("Result from GSA for url = {0}, result = {1}", absoluteQuery, result);

                var serializer = new JavaScriptSerializer();
                return serializer.DeserializeObject(result);
            }
            catch (Exception ex)
            {
                Log.Error("VideoCloud is not responsive", ex);
                return VideoResults.Empty;
            }
        }

        public object GetVideo(long videoId)
        {
            return GetResult(QueryUrlBuilder.Build(videoId));
        }
    }
}